/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Project  : MAC-Switcher
 * Package  : my.macswitcher.net
 * File     : NetProvider.java
 * Author   : Lei Duan < lei_d@foxmail.com >
 * Created  : 2011-5-15
 * License  : Apache License 2.0 
 */
package my.macswitcher.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.InputTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

public class NetProvider {
	private static NetProvider netProvider = null;
	private String code = "";
	private String password = "";
	private String acc = "";
	private String type = "";
	private String Submit = "登录";
	private String option = "login";
	private String imagex = "69";
	private String imagey = "16";

	private HttpClient httpClient = new DefaultHttpClient();
	private HttpResponse response;

	private NetProvider() {
		Init();
	}

	public static synchronized NetProvider getInstance() {
		if (netProvider == null) {
			NetProvider.netProvider = new NetProvider();
		}
		return netProvider;
	}

	private void Init() {
		HttpProtocolParams
				.setUserAgent(httpClient.getParams(),
						"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
		HttpGet index = new HttpGet(StaticVar.ENTRY_URL);
		try {
			httpClient.execute(index);
		} catch (Exception e) {
		} finally {
			index.abort();
		}
	}

	public byte[] getImage() {
		byte[] imgData = null;
		HttpGet img = new HttpGet(StaticVar.VERIFY_IMG_URL);
		try {
			response = httpClient.execute(img);
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		} finally {
			img.abort();
		}
		try {
			imgData = EntityUtils.toByteArray(response.getEntity());
		} catch (Exception e) {
		}
		return imgData;
	}

	public void login(String acc, String pwd, String type, String code) {
		this.acc = acc;
		this.password = pwd;
		this.type = type;
		this.code = code;

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("acc", this.acc));
		nvps.add(new BasicNameValuePair("code", this.code));
		nvps.add(new BasicNameValuePair("option", this.option));
		nvps.add(new BasicNameValuePair("passwd", this.password));
		nvps.add(new BasicNameValuePair("Submit", this.Submit));
		nvps.add(new BasicNameValuePair("type", this.type));

		HttpPost login = new HttpPost(StaticVar.LOGIN_URL);

		try {
			login.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			response=httpClient.execute(login);
		} catch (Exception e) {
		} finally {
			login.abort();
		}
	}

	public void changMAC(String mac) {
		String data = "";
		String event = "";
		String view = "";

		HttpGet getPage = new HttpGet(StaticVar.Chg_MAC_URL);
		try {
			response = httpClient.execute(getPage);
			data = EntityUtils.toString(response.getEntity());
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		} finally {
			getPage.abort();
		}
		// ////begin to parse the data to get __VIEWSTATE and __EVENTVALIDATION
		// which generate by asp.net
		try {
			Parser myParser = new Parser(data);
			myParser.setEncoding("utf-8");
			NodeList lists = null;
			NodeFilter filter = new NodeClassFilter(InputTag.class);
			lists = myParser.parse(filter);
			for (int i = 0; i < lists.size(); i++) {
				InputTag input = (InputTag) lists.elementAt(i);
				String name = input.getAttribute("name");
				String value = input.getAttribute("value");
				if (name.equals("__VIEWSTATE")) {
					view = value;
				}
				if (name.equals("__EVENTVALIDATION")) {
					event = value;
				}
			}
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println("event:"+event);
//		System.out.println("view:"+view);
		HttpPost postData = new HttpPost(StaticVar.Chg_MAC_URL);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		nvps.add(new BasicNameValuePair("__EVENTVALIDATION", event));
		nvps.add(new BasicNameValuePair("__VIEWSTATE", view));
		nvps.add(new BasicNameValuePair("DropDownList1", mac));
		nvps.add(new BasicNameValuePair("ImageButton1.x", "69"));
		nvps.add(new BasicNameValuePair("ImageButton1.y", "16"));

		try {
			postData.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			httpClient.execute(postData);
		} catch (Exception e) {
			// e.printStackTrace();
		} finally {
			postData.abort();
		}

	}

	public void shutDown() {
		this.httpClient.getConnectionManager().shutdown();
	}

}
